package com.maychat.controller;

import com.maychat.controller.base.BaseController;
import com.maychat.enums.ContactType;
import com.maychat.enums.MessageType;
import com.maychat.enums.UserContactStatus;
import com.maychat.enums.UserStatus;
import com.maychat.exception.BusinessException;
import com.maychat.exception.NoAuthException;
import com.maychat.pojo.*;
import com.maychat.service.GroupInfoService;
import com.maychat.service.UserContactService;
import com.maychat.service.UserInfoService;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/group")
public class GroupInfoController extends BaseController {
    @Autowired
    private GroupInfoService groupInfoService;

    @Autowired
    private UserContactService userContactService;

    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/save")
    public Result saveGroupInfo(@NotBlank String groupName,
                                String groupId,
                                String groupNotice,
                                Integer joinType,
                                MultipartFile avatarSmall,
                                MultipartFile avatarFull) throws NoAuthException, BusinessException, IOException {
        UserInfoToken tokenObj = getTokenObj();
        GroupInfo groupInfo = new GroupInfo(groupId, groupName, tokenObj.getUserId(), LocalDateTime.now(), groupNotice, joinType, UserStatus.ENABLED.ordinal());
        groupInfoService.saveGroup(groupInfo, avatarSmall, avatarFull);
        return Result.success();
    }

    @GetMapping("/getMyGroups")
    public Result getMyGroups() throws NoAuthException, BusinessException {
        UserInfoToken tokenObj = getTokenObj();
        List<GroupInfo> myGroups = groupInfoService.getMyGroups(tokenObj.getUserId());
        return Result.success(myGroups);
    }

    private GroupInfo getGroupInfoCommon(@NotBlank String groupId) throws NoAuthException, BusinessException {
        UserInfoToken tokenObj = getTokenObj();
        UserContact query = new UserContact();
        query.setUserId(tokenObj.getUserId());
        query.setContactId(groupId);
        List<UserContact> userContacts = userContactService.selectUserContacts(query);
        if (userContacts.isEmpty() || userContacts.get(0).getStatus() != UserContactStatus.FRIEND.ordinal())
            throw new BusinessException("你不在群聊中，或群聊已经解散");
        GroupInfo groupInfo = groupInfoService.selectGroupInfoById(groupId);
        if (groupInfo == null || UserStatus.DISABLED.ordinal() == groupInfo.getStatus())
            throw new BusinessException("群聊不存在，或群聊已经解散");
        Integer memberCount = groupInfoService.selectGroupMemberCount(groupId);
        groupInfo.setMemberCount(memberCount);
        return groupInfo;
    }

    @GetMapping("/getGroupInfo")
    public Result getGroupInfo(@RequestParam @NotBlank String groupId) throws NoAuthException, BusinessException {
        GroupInfo groupInfo = getGroupInfoCommon(groupId);
        return Result.success(groupInfo);
    }

    @GetMapping("/getGroupInfo4Chat")
    public Result getGroupInfo4Chat(@NotBlank String groupId) throws NoAuthException, BusinessException {
        GroupInfo groupInfo = getGroupInfoCommon(groupId);
        UserContact query = new UserContact();
        query.setContactId(groupId);
        query.setStatus(UserContactStatus.FRIEND.ordinal());
        query.setContactType(ContactType.GROUP.ordinal());
        List<UserInfo> userInfoList = userInfoService.selectUserInfosByUserContact(query);
        Map<String, Object> mp = new HashMap<>();
        mp.put("userInfoList", userInfoList);
        mp.put("groupInfo", groupInfo);
        return Result.success(mp);
    }

    /**
     * @param ids    数组
     * @param action 0就是拉人，1就是踢人
     */
    @PostMapping("/changeGroupMember")
    public Result changeGroupMember(@NotBlank String groupId, @RequestParam @NotEmpty ArrayList<String> ids,
                                    @NotNull Integer action) throws NoAuthException, BusinessException {
//        if (ids.isEmpty()) throw new BusinessException();
        UserInfoToken tokenObj = getTokenObj();
        groupInfoService.changeGroupMember(tokenObj.getUserId(), groupId, ids, action);
        return Result.success();
    }

    @PostMapping("/leaveGroup")
    public Result leaveGroup(@NotBlank String groupId) throws NoAuthException, BusinessException {
        UserInfoToken tokenObj = getTokenObj();
        groupInfoService.leaveGroup(tokenObj.getUserId(), groupId, MessageType.LEAVE_GROUP);
        return Result.success();
    }

    @DeleteMapping("/dissolveGroup")
    public Result dissolveGroup(@NotBlank String groupId) throws NoAuthException, BusinessException {
        UserInfoToken tokenObj = getTokenObj();
        groupInfoService.dissolveGroup(groupId, tokenObj.getUserId());
        return Result.success();
    }
}
